package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: autoSMSTemplate
 * @description: 自动同步云片短信模板
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class autoSMSTemplate implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoSMSTemplate.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String BATCH_ID = sdf.format(new Date()) + "_" + KHUtil.getRandomString(6).toUpperCase();

            // 普通账号模版同步
            int sync_Result = doYPTemplate(eliteBean, jt, "YUNPIAN_TZ_apiKey", BATCH_ID);
            log.debug("普通账号模版同步 结果:" + sync_Result);

            if (sync_Result > 0) {
                doDeleteHis(eliteBean, jt, "YUNPIAN_TZ_apiKey", BATCH_ID);
            }

            // 营销账号模版同步
            sync_Result = doYPTemplate(eliteBean, jt, "YUNPIAN_YX_apiKey", BATCH_ID);
            log.debug("营销账号模版同步 结果:" + sync_Result);

            if (sync_Result > 0) {
                doDeleteHis(eliteBean, jt, "YUNPIAN_YX_apiKey", BATCH_ID);
            }

            return true;
        } catch (Exception e) {
            log.error("自动获取短信平台模板异常-:" + e.getMessage(), e);
            return false;
        }

    }

    public static int doYPTemplate(EliteBean eliteBean, JdbcTemplate jt, String templateType, String BATCH_ID) {
        // 调用地址
        String sendURL = KHDBConfig.getAPIURL(eliteBean, "YUNPIAN-MSGTEMPLATE_URL").replace("#{apikey}", KHDBConfig.getParamConfig(eliteBean, templateType));
        log.debug("调用地址:" + sendURL);

        // 处理头文件
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Accept", "application/json;charset=utf-8");
        headerMap.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        log.debug("调用头文件:" + headerMap);

        String postResult = Util.doHttpPostUseHead(sendURL, "", "UTF-8", 120000, 0, headerMap);
        log.debug("调用返回结果：" + postResult);

        JSONArray templateArr = JSONArray.fromObject(postResult);

        // 标识全部云片模板无效 TODO
        for (int i = 0; i < templateArr.size(); i++) {

            String tpl_id = KHUtil.GetSFJV(templateArr.getJSONObject(i), "tpl_id");
            String tpl_content = KHUtil.GetSFJV(templateArr.getJSONObject(i), "tpl_content");
            String check_status = KHUtil.GetSFJV(templateArr.getJSONObject(i), "check_status");
            String reason = KHUtil.GetSFJV(templateArr.getJSONObject(i), "reason");
            String lang = KHUtil.GetSFJV(templateArr.getJSONObject(i), "lang");
            String country_code = KHUtil.GetSFJV(templateArr.getJSONObject(i), "country_code");
            log.debug("处理模板tpl_id:" + tpl_id + " tpl_content:" + tpl_content);

            String dealSQL = "select * from Doctemplate where tpl_id = ?";
            List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, tpl_id);

            log.debug("selectCus：" + selectCus);
            log.debug("检查数据(" + tpl_id + ") 数量：" + selectCus.size());

            String no_tpl_content = removePrefixWithRegex(tpl_content);
            String template_Title = tpl_content.substring(0, tpl_content.length() > 30 ? 30 : tpl_content.length() - 1);

            if (selectCus.size() == 0) {
                String insertSQL = '''Insert Into Doctemplate
                                          (Doctemplate_Id,
                                           Docgroup_Id,
                                           Description,
                                           Documentpath,
                                           Documentpath2,
                                           Status,
                                           Mailmerge,
                                           Doctype,
                                           Printtype,
                                           Dynid,
                                           Default_Flag,
                                           Tpl_Id,
                                           Check_Status,
                                           Reason,
                                           Apikey,
                                           Update_Time,
                                           Batch_Id)
                                        Values
                                          (?, 'XXXXXX', ?, ?, ?, 1, Null, 0, 'S', Null, Null, ?, ?, ?, ?, Now(), ?)''';
                int num = jt.update(insertSQL, KHUtil.getRandomString(6).toUpperCase(), template_Title, tpl_content, tpl_content, tpl_id, check_status, reason, templateType, BATCH_ID);
                log.debug("新增数据(" + tpl_id + ") 数量：" + num);
            } else {
                String updateSQL = '''Update Doctemplate
                                       Set Description = ?,
                                           Documentpath  = ?,
                                           Documentpath2 = ?,
                                           Status = Case
                                                      When ? = 'SUCCESS' Then
                                                       1
                                                      Else
                                                       0
                                                    End,
                                           Check_Status  = ?,
                                           Reason        = ?,
                                           Apikey        = ?,
                                           Update_Time   = Now(),
                                           Batch_Id      = ?
                                     Where Tpl_Id = ?''';
                int num = jt.update(updateSQL, template_Title, tpl_content, tpl_content, check_status, check_status, reason, templateType, BATCH_ID, tpl_id);
                log.debug("更新数据(" + tpl_id + ") 数量：" + num);
            }

        }
        return templateArr.size();

    }

    public static void doDeleteHis(EliteBean eliteBean, JdbcTemplate jt, String templateType, String BATCH_ID) {

        String[] del_SQLS = new String[2];

        del_SQLS[0] = '''Insert Into Doctemplate_His
  Select Uuid() Template_Guid,
         Doctemplate_Id,
         Docgroup_Id,
         Description,
         Documentpath,
         Documentpath2,
         Status,
         Mailmerge,
         Doctype,
         Printtype,
         Dynid,
         Default_Flag,
         Tpl_Id,
         Check_Status,
         Reason,
         Source,
         'BAKBAK' Createby,
         Now() Reateddate,
         Apikey
    From Doctemplate
   Where Apikey = \'''' + templateType + '''\'
     And Tpl_Id Is Not Null
     And Tpl_Id != \'\'
     And (Batch_Id != \'''' + BATCH_ID + '''\' Or Batch_Id Is Null Or Batch_Id = '')''';

        del_SQLS[1] = '''Delete From Doctemplate
 Where Apikey = \'''' + templateType + '''\'
   And Tpl_Id Is Not Null
   And Tpl_Id != \'\'
   And (Batch_Id != \'''' + BATCH_ID + '''\' Or Batch_Id Is Null Or Batch_Id = '')''';
        log.debug("清理未在同步范围的SQL:" + del_SQLS);

        int[] del_Res = eliteBean.updateBatch(del_SQLS, "dataSource");
        log.debug("清理未在同步范围的数据:" + del_Res);
    }

    /**
     * 使用正则表达式移除字符串开头的【...】标记
     * @param str 原始字符串
     * @return 移除标记后的字符串
     */
    public static String removePrefixWithRegex(String str) {
        // 检查字符串是否为空
        if (str == null || str.isEmpty()) {
            return str;
        }

        // 正则表达式：匹配以【开头，以】结尾的开头标记
        // ^表示字符串开始，【和】是标记的边界，.*?表示非贪婪匹配任意字符
        String regex = "^【.*?】";

        // 替换匹配到的内容为空字符串
        return str.replaceFirst(regex, "");
    }
}